/**
 * Copyright [2011] [Raymond Pankhurst]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */
package passwordapp;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator;

/**
 *
 * @author rpankhurst
 */
public class EncryptionUtils {
    public static CipherParameters createKey(String pw) {
        PKCS12ParametersGenerator key_gen = new PKCS12ParametersGenerator(new SHA1Digest());
        key_gen.init(pw.getBytes(), "salt".getBytes(), 10);
        return key_gen.generateDerivedParameters(192);
    }
    public static byte[] performEncrypt(CipherParameters key, byte[] ptBytes)
    {       
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

        String name = cipher.getUnderlyingCipher().getAlgorithmName();
        System.out.println("Using " + name);

        cipher.init(true, key);

        byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)];

        int oLen = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0);
        try
        {
            cipher.doFinal(rv, oLen);
        }
        catch (CryptoException ce)
        {
            System.out.println("Ooops, encrypt exception");
            System.out.println(ce.toString());
            rv = null;
        }
        return rv;
    }
    public static byte[] performDecrypt(CipherParameters key, byte[] cipherText)
    {
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        cipher.init(false, key);

        byte[] rv = new byte[cipher.getOutputSize(cipherText.length)];

        int oLen = cipher.processBytes(cipherText, 0, cipherText.length, rv, 0);
        try
        {
            cipher.doFinal(rv, oLen);
        }
        catch (CryptoException ce)
        {
            System.out.println("Ooops, decrypt exception");
            System.out.println(ce.toString());
            rv = null;
        }
        return rv;
    }
    
}
